
#include <BOpenGL>
#include "member_BRender.h"
#include "member_BLight.h"

using namespace BWE;

member_BRender::member_BRender(BRender* render)
{
	boss = render;
	camera = 0;
	light = 0;
	node = 0;
	shape = 0;
	material = 0;
	program = 0;
	bFill(tbos, 0, 10);

	depthOffset = 0.0f;
	polyMode = Poly_Fill;
	lighting = glIsEnabled(GL_LIGHTING);
	normalize = glIsEnabled(GL_NORMALIZE);
	depthTest = glIsEnabled(GL_DEPTH_TEST);
	cullback = glIsEnabled(GL_CULL_FACE);
	polySmooth = glIsEnabled(GL_MULTISAMPLE);
	lineSmooth = glIsEnabled(GL_LINE_SMOOTH);
	pointSmooth = glIsEnabled(GL_POINT_SMOOTH);
	glGetFloatv(GL_POINT_SIZE, &pointSize);
	glGetFloatv(GL_LINE_WIDTH, &lineWidth);
	glGetIntegerv(GL_LINE_STIPPLE, &lineStipple);
}
member_BRender::~member_BRender()
{

}

void member_BRender::useLights(const BBox& box)
{
	if (lights == 0)
		return;

	BLight* light_array[8];
	for (int i = 0; i < 8; i++)
	{
		light_array[i] = (*lights)(i);
	}
	for (int i = 0; i < 8; i++)
	{
		BLight* light = light_array[i];
		int index = GL_LIGHT0 + i;
		if (!light || !light->enabled())
		{
			if (i > 0)
				glDisable(index);
			continue;
		}
		glEnable(index);
		member_BLight* mem = light_member(light);
		glLightfv(index, GL_AMBIENT, (const GLfloat*)&light_member(light)->ambientColor);
		glLightfv(index, GL_DIFFUSE, (const GLfloat*)&light_member(light)->diffuseColor);
		glLightfv(index, GL_SPECULAR, (const GLfloat*)&light_member(light)->specularColor);
		glLightf(index, GL_CONSTANT_ATTENUATION, 1.0f);
		glLightf(index, GL_LINEAR_ATTENUATION, light_member(light)->attenuation);
		glLightf(index, GL_QUADRATIC_ATTENUATION, light_member(light)->attenuation2);

		BVector position = light->position();
		GLfloat pos[4] = { (GLfloat)position.x(), (GLfloat)position.y(), (GLfloat)position.z(), (GLfloat)1 };
		glLightfv(index, GL_POSITION, pos);

		BVector direct = light->direct();
		GLfloat dir[3] = { (GLfloat)direct.x(), (GLfloat)direct.y(), (GLfloat)direct.z() };
		glLightfv(index, GL_SPOT_DIRECTION, dir);

		glLightf(index, GL_SPOT_CUTOFF, light_member(light)->cutoff);
		glLightf(index, GL_SPOT_EXPONENT, light_member(light)->exponent);
	}
}
